import { Toast, MessageBox } from 'mint-ui';

//判断是不是手机号码
String.prototype.isMobile = function () {
  return /^1\d{10}$/.test(this);
};

//计算字符串长度
String.prototype.strLen = function () {
  var len = 0;
  for (var i = 0; i < this.length; i++) {
    if (this.charCodeAt(i) > 255 || this.charCodeAt(i) < 0) len += 2;
    else len++;
  }
  return len;
}
if (typeof String.prototype.startsWith != 'function') {
  String.prototype.startsWith = function (prefix) {
    return this.slice(0, prefix.length) === prefix;
  };
}

let Tools = {
  // 获取浏览器信息
  getBrowser: function () {
    return {
      versions: function () {
        var u = navigator.userAgent;
        return {
          trident: u.indexOf('Trident') > -1, //IE内核
          presto: u.indexOf('Presto') > -1, //opera内核
          webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
          gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
          mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
          ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
          android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, //android终端
          iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
          iPad: u.indexOf('iPad') > -1, //是否iPad
          webApp: u.indexOf('Safari') == -1, //是否web应该程序，没有头部与底部
          weixin: u.indexOf('MicroMessenger') > -1, //是否微信 （2015-01-22新增）
          qq: u.match(/\sQQ/i) == " qq" //是否QQ
        };
      }(),
      language: (navigator.browserLanguage || navigator.language).toLowerCase()
    };
  },
  showToast: function (msg) {
    Toast(msg);
  },

  showLoginBox: function () {
    MessageBox.confirm('您还没有登录，请登录之后继续操作！').then(action => {
      let Base64 = require('js-base64').Base64;
      let skip_url = Base64.encode(window.location.href);

      if (process.env.NODE_ENV == 'development') { //开发环境
        window.location.href = 'http://xueban.vstudy.net.cn/mp/login?skip_url=' + skip_url + '&share_user_id=' + '';
      } else {
        window.location.href = window.location.origin + '/mp/login?skip_url=' + skip_url + '&share_user_id=' + '';
      }

    }).catch((error) => {
      // console.log(error)
    });
  },
  // 获取渲染之后的图片地址
  getRenderImgUrl: function (value, width, height) {
    if (typeof value == 'undefined') {
      return '';
    }
    let fix_w_h = '';
    if (value.indexOf('http://') != -1 || value.indexOf('https://') != -1) {
      if (typeof width != 'undefined' && typeof width != 'undefined') {
        fix_w_h = '?imageView2/1/w/' + width + '/h/' + height;
      }
      return value + fix_w_h;
    }

    if (typeof width != 'undefined' && typeof width != 'undefined') {
      fix_w_h = '/' + width + '/' + height;
    }
    return 'http://image.imoocs.org/image/upload_web/' + value + fix_w_h;
  },

  getStrLen: function (str) {
    if (str && typeof str == 'string') {
      var realLength = 0,
        len = str.length,
        charCode = -1;
      for (var i = 0; i < len; i++) {
        charCode = str.charCodeAt(i);
        if (charCode >= 0 && charCode <= 128) realLength += 1;
        else realLength += 2;
      }
      return realLength;
    }
  },
  cutStr: function (str, len) { //获取指定长度 str
    try {
      var str_length = 0;
      var str_len = 0;
      str_cut = new String();
      str_len = str.length;
      for (var i = 0; i < str_len; i++) {
        a = str.charAt(i);
        str_length++;
        if (escape(a).length > 4) {
          //中文字符的长度经编码之后大于4
          str_length++;
        }
        if (str_length > len) {
          // str_cut = str_cut.concat("");
          return str_cut;
        }
        str_cut = str_cut.concat(a);
      }
      //如果给定字符串小于指定长度，则返回源字符串；
      if (str_length <= len) {
        return str;
      }
    } catch (ex) {
      return str;
    }
  },

  //获取url中"?"符后的所有参数
  getRequest: function () {
    var url = window.location.search; //获取url中"?"符后的字串
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
      var str = url.substr(1),
        strs = str.split("&");
      for (var i = 0; i < strs.length; i++) {
        theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
      }
    }
    return theRequest;
  },
  numToDBNum: function (num) {
    return num < 10 ? ("0" + num) : num;
  },
  getResourceNameByType: function (type) {
    var str = '';
    type = parseInt(type)
    switch (type) {
      case 0:
        str = '视频慕课';
        break;
      case 31:
        str = '视频直播';
        break;
      case 56:
        str = '语音直播';
        break;
      case 52:
        str = '专辑';
        break;
      case 53:
        str = '语音微课';
        break;
    }
    return str;
  },
  // 资源统称 
  getUnifiedNameByType: function (type) {
    var str = '';
    type = parseInt(type)
    switch (type) {
      case 0:
        str = '课程';
        break;
      case 31:
        str = '直播';
        break;
      case 56:
        str = '直播';
        break;
      case 52:
        str = '专辑';
        break;
      case 53:
        str = '课程';
        break;
    }
    return str;
  },
  getWkUrlByType: function (type) {
    var str = '';
    switch (type) {
      case 0:
        str = '/mooc/detail/';
        break;
      case 31:
        str = '/live/video/detail/';
        break;
      case 56:
        str = '/live/audio/detail/';
        break;
      case 52:
        str = '/special/detail/';
        break;
      case 53:
        str = '/micro/detail/';
        break;
    }
    return str;
  },
  // 跳转机构主页
  skipTeamHome: function (team_id) {
    let skip_team_url = process.env.NODE_ENV == 'development' ? 'http://xueban.vstudy.net.cn' : window.location.origin,
      t_home_path = '/mp/ekp';

    let request_params = this.getRequest();
    if (request_params['wmuserid']) { // app完美定制
      t_home_path = '/wanxiao/home';
    }
    skip_team_url += t_home_path + '?f_t_id=' + team_id;

    if (window.location.search != '') { //如果链接参数不为空
      let params_str = '';
      for (var key in request_params) {
        if (key == "f_t_id") {
          continue;
        }
        params_str += '&' + key + "=" + request_params[key];
      }

      skip_team_url += params_str;
    }
    // console.log(skip_team_url)
    window.location.href = skip_team_url + '#/';
  },

  // 生成授权地址，获取openid  V2版本,二次授权
  getOauth2Url: function (mp_id, flag_type, xb_userid) {
    flag_type = flag_type || 'menu';
    xb_userid = xb_userid || '';

    let Base64 = require('js-base64').Base64;
    let origin = process.env.NODE_ENV == 'development' ? 'http://xueban.vstudy.net.cn' : window.location.origin;

    let redirect_list = [
      origin,
      '/mp/common/oauth2_v2?final_url=',
      Base64.encode(window.location.href),
      '&flag_type=' + flag_type,
      '&mp_id=' + mp_id
    ];
    if (flag_type == 'relate_auth') {
      redirect_list.push('&xb_userid=' + xb_userid)
    }
    
    let req_params = this.getRequest();
    if(req_params['share_user_id']){
      redirect_list.push('&share_user_id=' + req_params['share_user_id'])
    }

    return redirect_list.join('')
  },

  getViewportSize: function () {
    return {
      width: window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
      height: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
    };
  },

  dateFormat: function (value, format) {
    if (!Date.prototype.Format) {
      Date.prototype.Format = function (fmt) {
        var o = {
          "M+": this.getMonth() + 1, //月份
          "d+": this.getDate(), //日
          "h+": this.getHours(), //小时
          "m+": this.getMinutes(), //分
          "s+": this.getSeconds(), //秒
          "q+": Math.floor((this.getMonth() + 3) / 3), //季度
          "S": this.getMilliseconds() //毫秒
        };
        if (/(y+)/.test(fmt))
          fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
          if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
      }
    }

    format = format || 'yyyy-MM-dd hh:mm:ss';

    return new Date(value).Format(format);
  },
  // 优惠券状态
  showCouponState: function (end_time, server_time) {
    if (end_time == -1) {//未定义有效时间
      return 0; //正常
    }

    if (end_time > 0) {
      if (end_time < server_time) { //已经失效
        return 2;
      } else if (end_time - server_time < 3 * 24 * 3600) { //距离截止时间，提前3天的时间戳  //即将过期
        return 1;
      }

      return 0;
    }
  },

  //调用原生
  callNative: function (code, data) {
    window.appWecastClient.getJsData(JSON.stringify({
      code: code,
      data: data
    }));
  }

};

export default Tools